<?php
namespace app\admin\controller;;

class Login {
    public function login(){
        $params = request()->post();
        $account = isset($params['account']) ? trim($params['account']) : '';
        if($account === ''){
            return errorResult('请输入登录账号');
        }
        
        $password = isset($params['password']) ? trim($params['password']) : '';
        
        if(32 != strlen($password)){
            return errorResult('请输入密码');
        }
        $password = strtolower($password);

        $role = isset($params['role']) ? intval($params['role']) : 1;
        if(!in_array($role, [1, 2, 3])){
            return errorResult();
        }
        
        $field = ['password', 'salt'];
        if($role == 1) {
            $adminModel = model('Admin');
            $where = ['account' => $account];
            $field[] = 'id';
        }elseif($role == 2) {
            $adminModel = model('Agent');
            $where = ['agent_account' => $account];
            $field[] = 'agent_id';
        }else {
            $adminModel = model('Store');
            $where = ['store_account' => $account];
            $field[] = 'store_id';
        }
        
        
        
        $admin = $adminModel->where($where)->field($field)->find();
        if(!$admin){
            return errorResult('用户名或密码错误');
        }

        $password = md5(md5($password) . $admin['salt']);
        if($password !== $admin['password']){
            return errorResult('用户名或密码错误');
        }
        
        
        if($role == 1) {
            $userId = $admin['id'];
        }elseif($role == 2) {
            $userId = $admin['agent_id'];
        }else {
            $userId = $admin['store_id'];
        }
        
        $signer = new \Lcobucci\JWT\Signer\Hmac\Sha256();
        $builder = new \Lcobucci\JWT\Builder();
        $builder->setIssuer('尚e充');
        $builder->setAudience('尚e充');
        $builder->setId($userId * 520, true); //自定义标识
        $builder->setIssuedAt(time());
        $builder->set('key', base64_encode($userId * 1314));
        $builder->set('role', $role);
        $builder->sign($signer, '@#$%^&*qwe%r&t^yuio===');
        $token = $builder->getToken()->__toString();
        $repdata = ['token'=>$token,'name'=>'Super Admin'];
        return successResult($repdata);
    }
}